﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace H.Kernel.Utils
{
    /// <summary>
    /// 进程工具
    /// </summary>
    public static class ProcessUtil
    {
        [Flags]
        public enum ShowCommands : int
        {
            SW_HIDE = 0,
            SW_SHOWNORMAL = 1,
            SW_NORMAL = 1,
            SW_SHOWMINIMIZED = 2,
            SW_SHOWMAXIMIZED = 3,
            SW_MAXIMIZE = 3,
            SW_SHOWNOACTIVATE = 4,
            SW_SHOW = 5,
            SW_MINIMIZE = 6,
            SW_SHOWMINNOACTIVE = 7,
            SW_SHOWNA = 8,
            SW_RESTORE = 9,
            SW_SHOWDEFAULT = 10,
            SW_FORCEMINIMIZE = 11,
            SW_MAX = 11
        }

        private static class NativeMethods
        {
            [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
            public static extern IntPtr ShellExecute(
                IntPtr hwnd,
                string lpOperation,
                string lpFile,
                string lpParameters,
                string lpDirectory,
                ShowCommands nShowCmd);
        }

        /// <summary>
        /// 开始一个新的进程
        /// </summary>
        /// <param name="file">需要打开的文件</param>
        /// <param name="param">启动参数</param>
        /// <param name="directory">初始文件夹</param>
        public static void Start(string file, string param = "", string directory = "")
        {
            NativeMethods.ShellExecute(IntPtr.Zero, "open", file, param, directory, ShowCommands.SW_SHOWNORMAL);
        }

        /// <summary>
        /// 根据进程名称查找进程
        /// </summary>
        /// <param name="procName"></param>
        /// <returns></returns>
        public static Process[] GetByName(string procName)
        {
            if (procName.Contains(".exe"))
            {
                return Process.GetProcessesByName(procName.Substring(0, procName.IndexOf(".exe")));
            }
            else
            {
                return Process.GetProcessesByName(procName);
            }
        }

        /// <summary>
        /// 检查某个进程是否存在
        /// </summary>
        /// <param name="procName"></param>
        /// <returns></returns>
        public static bool Exists(string procName)
        {
            if (procName.Contains(".exe"))
            {
                return Process.GetProcessesByName(procName.Substring(0, procName.IndexOf(".exe"))).Length > 0;
            }
            else
            {
                return Process.GetProcessesByName(procName).Length > 0;
            }
        }

        /// <summary>
        /// 杀死所有名称为<paramref name="procName"/>的进程
        /// </summary>
        /// <param name="procName"></param>
        public static void Kill(string procName)
        {
            foreach (Process process in GetByName(procName))
            {
                process.Kill();
            }
        }
    }
}
